<template>
  <div class="eleMap">
    <div id="viewDiv">
      <div class="setPoint">
        <span id="pointButton" class="action-button esri-icon-blank-map-pin esri-widget-button esri-widget esri-interactive" type="button" title="画点"></span>
        <span id="polygonButton" class="action-button esri-icon-polygon esri-widget-button esri-widget esri-interactive" type="button" title="画三圈"></span>
      </div>
    </div>
  </div>
</template>

<script>
  import * as esriLoader from 'esri-loader';

  export default {
    name: "threeCircles",
    props:{
      lineSymbolColor: {
        type: String,
        default: '#fff'
      },
      lineSymbolWidth: {
        type: String,
        default: 4
      },
      lineSymbolStyle: {
        type: String,
        default: 'solid'
      },
      rings: Array,
      pointDataStr: String,
      isClearDeleteDataMap: Boolean
    },
    data () {
      return {
        view: null,
        _polygon: null,
        pointAddTag: false,     // 是否能够打点标志位
        _geometryEngine: null,
        tempGraphicsLayer: null, // 临时图形存放layer
        graphicData: null,       // 圈得存放数据
      }
    },
    created(){
      esriLoader.loadCss(cssURL);
    },
    mounted () {
      this.createMap();
    },
    computed:{

    },
    methods: {
      createMap () {
        // 引入依赖
        //debugger;
        esriLoader.loadModules([
          'esri/Map',
          'esri/views/MapView',
          'esri/layers/GraphicsLayer',
          'esri/widgets/Sketch/SketchViewModel',
          "esri/geometry/geometryEngine",
          "esri/geometry/Point",
          "esri/geometry/Polygon",
          'esri/layers/TileLayer',
          "esri/Basemap",
          'esri/Graphic'
        ], {url:dojoURL}).then(([EsriMap, MapView, GraphicsLayer, SketchViewModel, geometryEngine, Point, Polygon, TileLayer, Basemap, Graphic]) => {
          var self = this;
          self._geometryEngine = geometryEngine;
          let test = false;
          //debugger;
          if(test){
            this.map = new EsriMap({
              basemap: 'streets'
            })
          }
          else {
            //console.log(mapServer);
            var layer = new TileLayer({


              url:mapServer
            })
            var customBasemap = new Basemap({
              baseLayers: [layer],
              title: 'geometries',
              id: 'geometries'
            })
            this.map = new EsriMap({
              basemap: customBasemap
            })
          }

          let updateGraphic
          self.tempGraphicsLayer = new GraphicsLayer()
          this.map.add(self.tempGraphicsLayer, 1)
          this.view = new MapView({
            container: 'viewDiv',
            center: g_centerPoint,
            zoom: 5,
            map: this.map
          })
         // let pointSymbol = { // symbol used for points
         //   type: 'simple-marker', // autocasts as new SimpleMarkerSymbol()
         //   style: 'square',
         //   color: '#8A2BE2',
         //   size: '15px',
         //   outline: { // autocasts as new SimpleLineSymbol()
         //     color: [255, 255, 255],
         //     width: 2 // points
         //   }
         // }
          let pointSymbol = {
            type: 'picture-marker', // autocasts as new PictureMarkerSymbol()
            url:  'static/img/location_point.png',
            width: '40px',
            height: '40px',
            xoffset: 2,
            yoffset: 12,
          }

          let polylineSymbol = {
            type: 'simple-line', // autocasts as new SimpleLineSymbol()
            color: '#8A2BE2',
            width: '4',
            style: 'solid'
          }

          // edit
          if(this.rings){
            let geometry = new Polygon({
              hasZ: false,
              hasM: true,
              rings: this.rings,
              spatialReference: { wkid: 4326 }
            })
            // 修改中心点
            self.view.center = self.rings[0][self.rings[0].length-1];
            DrawGeometry(geometry);
            let pointDataAry = JSON.parse(this.pointDataStr);
            if( pointDataAry.length > 0 ){
              pointDataAry.forEach(function(item){
                let pointDataAryGraphic = new Graphic({
                  geometry: {
                    type: "point",
                    longitude:item.longitude,
                    latitude: item.latitude
                  },
                  symbol: pointSymbol
                })
                pointDataAryGraphic.attributes = {
                  'uid': item.uid
                }
                self.view.graphics.add(pointDataAryGraphic);
                //console.log(self.view.graphics.items)
              });
            }
          }

          this.view.when(function (evt) {
            let sketchViewModel = new SketchViewModel({
              view: self.view,
              layer: self.tempGraphicsLayer,
              pointSymbol: {
                type: "simple-marker", // autocasts as new SimpleMarkerSymbol()
                style: "circle",
                color: "#8A2BE2",
                size: "12px", // pixels
                outline: { // autocasts as new SimpleLineSymbol()
                  color: [ 255, 255, 255],
                  width: 3 // points
                }
              },
            })

            setUpClickHandler()
            sketchViewModel.on('draw-complete', addGraphic)
            sketchViewModel.on('update-complete', addGraphic)
            sketchViewModel.on('update-cancel', addGraphic)
            let pointButton = document.getElementById('pointButton')
            let drawPolygonButton = document.getElementById('polygonButton')
            clickButton(pointButton, 'point')
            clickButton(drawPolygonButton, 'polygon')
            function clickButton (button, type) {
              button.onclick = function () {
                if(type == 'point'){
                  if(self.tempGraphicsLayer.graphics.items.length === 0){
                    self._polygon = null;
                  }
                  sketchViewModel.reset();
                  self.pointAddTag = true;
                  // 把鼠标变成十字
                  $('#viewDiv')[0].style.cursor = 'crosshair'
                }
                else {
                  self.pointAddTag = false;
                  // self.view.graphics.removeAll();
                  sketchViewModel.reset()
                  self.tempGraphicsLayer.removeAll()
                  sketchViewModel.create(type)
                  setActiveButton(this)
                }
              }
            }
            function setActiveButton (selectedButton) {
              // focus the view to activete keyboard shortcuts for sketching
              self.view.focus()
              let elements = document.getElementsByClassName('active')
              for (let i = 0; i < elements.length; i++) {
                elements[i].classList.remove('active')
              }
              if (selectedButton) {
                selectedButton.classList.add('active')
              }
            }
            function setUpClickHandler () {
              self.view.on('click', function (evt) {
                // view.hitTest(evt).then(function (response) {
                //   let results = response.results
                //   if (results.length && results[results.length - 1].graphic) {
                //     if (!updateGraphic) {
                //       updateGraphic = results[results.length - 1].graphic
                //       self.tempGraphicsLayer.remove(updateGraphic)
                //       sketchViewModel.update(updateGraphic.geometry)
                //     }
                //   }
                // })
                if(self.pointAddTag){
                  var temporaryPt = new Point({
                    type: "point", // autocasts as new Point()
                    longitude: parseFloat(evt.mapPoint.longitude.toFixed(8)),
                    latitude: parseFloat(evt.mapPoint.latitude.toFixed(8)),
                  });
                  var temporaryPtGraphic = new Graphic({
                    geometry: temporaryPt,
                    symbol: pointSymbol
                  })
                  temporaryPtGraphic.attributes = {
                    'uid': temporaryPtGraphic.uid
                  }
                  // self.view.graphics.add(temporaryPtGraphic);

                  if(self._polygon){ // 有圈
                    var within = self.withinFn( temporaryPt, self._polygon );
                    if(within){
                      self.view.graphics.add(temporaryPtGraphic);
                      self.$emit('addPointData',temporaryPtGraphic);
                    }else{
                      self.s_alert('点不在图形内，请重新画点')
                    }
                    //console.log(within);
                    //console.log("*******")
                  } else { // 没有圈
                    self.view.graphics.add(temporaryPtGraphic);
                    self.$emit('addPointData',temporaryPtGraphic);
                  }
                  self.pointAddTag = false;
                  // 把鼠标变成默认
                  $('#viewDiv')[0].style.cursor = 'default'
                  //console.log(self.view.graphics.items, 'items');
                }
              })
            }
          })
          function addGraphic (evt) {
            let geometry = evt.geometry
            DrawGeometry(geometry);
          };
          function DrawGeometry(geometry){
            let polygonSymbol = { // symbol used for polygons
              type: 'simple-fill', // autocasts as new SimpleFillSymbol()
              color: 'rgba(138,43,226, 0.8)',
              style: 'solid',
              outline: {
                color: self.lineSymbolColor,
                width: parseInt(self.lineSymbolWidth),
                style: self.lineSymbolStyle
              }
            }
            let symbol
            if (geometry.type === 'point') {
              symbol = pointSymbol
            } else if (geometry.type === 'polyline') {
              symbol = polylineSymbol
            }
            else {
              symbol = polygonSymbol
              self._polygon = new Polygon(geometry)
            }
            var graphic = new Graphic({
              geometry: geometry,
              symbol: symbol
            })

            // 画好圈的时候如果先打了点就要判断点是否在圈内
            let itemsWithinFlag = true;
            if(self.view.graphics.items){
              for(let i = 0; i < self.view.graphics.items.length; i++){
                if(!self.withinFn(self.view.graphics.items[i].geometry, self._polygon)){
                  self.s_alert('有部分点不在圈内，请重新画');
                  // 清空self._polygon
                  self._polygon = null;
                  itemsWithinFlag = false;
                  return false;
                }
              }
            }

            if(itemsWithinFlag){
              self.tempGraphicsLayer.add(graphic);
              self.graphicData = graphic;
              var json = graphic.toJSON();
              self.$emit("graphicJSON",json);
              //console.log(JSON.stringify(json));
              updateGraphic = null
            }


          };

        })
      },
      // 是否包含
      withinFn( innerGeometry, outerGeometry){
        return this._geometryEngine.within( innerGeometry, outerGeometry );
      },
      // 删除点
      deletePoint(uid){
        let items = this.view.graphics.items;
        for(let i = 0; i < items.length; i++){
          if(items[i].attributes.uid === uid){
            this.view.graphics.remove(items[i]);
          }
        }
        //console.log(this.view.graphics.items, uid)
      },
      // 改变圈边线颜色
      changeOutline(){
        let self = this;
        self.tempGraphicsLayer.remove(self.graphicData);
        self.graphicData.symbol.outline.color = self.lineSymbolColor;
        self.graphicData.symbol.outline.width = self.lineSymbolWidth;
        self.graphicData.symbol.outline.style = self.lineSymbolStyle;
        this.$nextTick(function(){
          self.tempGraphicsLayer.add(self.graphicData);
        })
      },
      // 清除地图数据
      clearMap () {
        this.view = null;
        this._polygon = null;
        this.pointAddTag = null;
        this._geometryEngine = null;
        this.tempGraphicsLayer = null;
        this.graphicData = null;
      }
    },
    watch:{
      rings: {
        handler: function(){
          this.createMap()
        },
        deep: true
      },
      lineSymbolColor(){
        if(this._polygon){
          this.changeOutline();
        }
      },
      lineSymbolWidth(){
        if(this._polygon) {
          this.changeOutline();
        }
      },
      lineSymbolStyle(){
        if(this._polygon) {
          this.changeOutline();
        }
      },
      isClearDeleteDataMap(val) {
        if(val){
          this.clearMap();
        }
      }
    }
  }
</script>

<style scoped>
  .eleMap {
    width: 100%;
    height: 100%;
  }
  #viewDiv {
    width: 100%;
    height: 100%;
    z-index: -1;
  }
  .action-button {
    font-size: 16px;
    background-color: white;
    border: 1px solid #D3D3D3;
    color: #6e6e6e;
    height: 32px;
    width: 32px;
    text-align: center;
    box-shadow: 0 0 1px rgba(0, 0, 0, 0.3);
  }

  .action-button:hover,
  .action-button:focus {
    background: #0079c1;
    color: #e4e4e4;
  }
  .setPoint{
    position: absolute;
    top: 79px;
    left: 14px;
    z-index: 100;
  }
</style>
